package cn.shop.dys.fragment;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;

import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.shop.dys.bean.AddressInfo;
import cn.shop.dys.constant.CommonConstant;
import cn.shop.lib_common.CommonUtil;
import cn.shop.dys.R;
import cn.shop.dys.adapter.AddressAdapter;
import cn.shop.dys.constant.SPConstant;
import cn.shop.dys.util.SPUtil;


/**
 * 用户地址处理
 * Created by jian on 2016/4/19.
 */
public class UserDetailsAddressFragment extends BaseFragment{
    private OnUserDetailsClickListener mListener;
    @ViewInject(R.id.lv_details_address_list)
    private ListView mAddressList;
    @ViewInject(R.id.bt_add_address)
    private Button mAddAddress;
    private Context mContext;
    @ViewInject(R.id.rl_address_list_empty)
    private View mAddressListEmpty;
   // private UserInfo mUserInfo;
    private String mUserId;
    private OnAddressInfoTransferListener mTransferListener;

    @Override
    public View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_user_details_address,null);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        mContext = getActivity();
      //  UserInfo userInfo = getUserInfo();
       /* Log.d("test", userInfo.toString());
        if(userInfo!=null){
            mUserInfo = userInfo;
        }*/
       // UserInfo userInfo = mUserInfoDao.getUserInfo(SPUtil.getString(mContext, SPConstant.USER_INFO_USER_ID));
        mUserId = SPUtil.getString(mContext, SPConstant.USER_INFO_USER_ID);
       // Log.d("test",userId);
       /* UserInfo userInfo = UserInfoDBUtil.queryUserInfoByUserId(userId);
        if(mUserInfo!=null){
            mUserInfo=userInfo;
        }*/
        init();
    }

    private void init() {
        initListView();
        initEvent();
    }

    private void initListView() {
        /*List<String> infos=new ArrayList<String>();

        for (int i = 0; i < 30; i++) {
            infos.add("我是收货地址");
        }
        mAddressList.setAdapter(new ArrayAdapter<String>(mContext,
                android.R.layout.simple_list_item_1, infos));*/
        mAddressList.setEmptyView(mAddressListEmpty);
        mAddressList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //  Log.d("test", "hehhe");
                if (mListener != null) {
                    mListener.onClick(4);
                    if (mTransferListener != null) {
                        //传递地址信息
                        mTransferListener.transferAddressInfo(mAddressInfos.get(position));
                    }
                }
            /*    Intent intent =new Intent(mContext, UserDetailsActivity.class);
                intent.putExtra("index",4);
                mContext.startActivity(intent);*/
            }
        });
        getAddressList(mUserId);
    }

   /* @Override
    public void onResume() {
        super.onResume();
        Log.d("test","刷新");

    }*/
    private boolean isFirst=true;
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(isVisibleToUser){
            if(!isFirst){
                Log.d("test", "刷新1");
                getAddressList(mUserId);
            }
            isFirst=false;
        }
    }

    private void initEvent() {
        mAddAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mListener != null) {
                    mListener.onClick(3);
                }
            }
        });
    }
    public void setOnAddressInfoTransferListener(OnAddressInfoTransferListener transferListener){
        this.mTransferListener=transferListener;
    }
    public interface OnAddressInfoTransferListener{
        void transferAddressInfo(AddressInfo addressInfos);
    }
    @Override
    public void setOnUserDetailsClickListener(OnUserDetailsClickListener listener) {
        this.mListener=listener;
    }
    private AddressAdapter mAddressAdapter;
    private void setAdapter(){
        if(mAddressAdapter==null){
            mAddressAdapter=new AddressAdapter(mAddressInfos,mContext);
            mAddressList.setAdapter(mAddressAdapter);
        }else {
            mAddressAdapter.notifyDataSetChanged();
          //  mAddressList.setSelection(mAddressAdapter.getCount());
        }
    }
    /**
     * 获取地址信息
     * 作者:孙建
     * created at 2016/4/21 19:20
     */
    private List<AddressInfo> mAddressInfos=new ArrayList<>();
    private void getAddressList(String userid) {
        mHttpUtils.configDefaultHttpCacheExpiry(0);
        mHttpUtils.configTimeout(10000);
        RequestParams params = new RequestParams();
        params.addHeader("userid", userid);
        mHttpUtils.send(HttpRequest.HttpMethod.POST, CommonConstant.HOST_ADDRESSLIST, params,
                new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        int statusCode = responseInfo.statusCode;
                        if (statusCode == 200) {
                            String result = responseInfo.result;
                           // Log.d("test","test1"+result.toString());
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                String response = jsonObject.getString("response");
                            //    String error = jsonObject.getString("error");
                                if (response.equals("addressList")) {
                                  //  List<AddressInfo> addressInfos= (List<AddressInfo>) jsonObject.get("addressList");
                                //    Log.d("test","1");
                                    String addressList = jsonObject.getString("addressList");
                                 //  Log.d("test", "test2" + addressList);
                                    List<AddressInfo> addressInfos= mGson.fromJson(addressList,new TypeToken<List<AddressInfo>>(){}.getType());
                                 //   JSONArray addressList = new JSONArray("addressList");
                                 //   String s = addressList.toString();
                                    //  String addressList = jsonObject.getString("addressList");
                                   // List<AddressInfo> addressInfos = myResponseInfo.getAddressInfos();
                                 // Log.d("test","test3" +addressInfos.toString());
                                    if (addressInfos!= null) {
                                        mAddressInfos.clear();
                                        mAddressInfos.addAll(addressInfos);
                                        setAdapter();
                                    }
                                }else {
                                    if(response.equals("userid请求头为空")){
                                        CommonUtil.showToast(mContext, "请登录");
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                         //   MyResponseInfo myResponseInfo = mGson.fromJson(result, MyResponseInfo.class);
                        } else {
                            CommonUtil.showToast(mContext, "请求失败:错误码为"+statusCode);
                        }

                    }
                    @Override
                    public void onFailure(HttpException error, String msg) {
                        CommonUtil.showToast(mContext, "网络未连接:"+msg);
                    }

                });

    }
}
